package cn.jasonone.hm.netdisc.converter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author Jason
 * @date 2020-07-22 15:28:47
 */
@Slf4j
@Component
public class DateConverter implements Converter<String, Date> {
	//Wed Jul 22 15:33:17 CST 2020
	private static final String PATTERN_DEFAULT_FORMAT="EEE MMM dd HH:mm:ss ZZZ yyyy";
	
	private static final String PATTERN_DATE="\\d{4}-\\d{2}-\\d{2}";
	
	private static final String PATTERN_DATE_FORMAT="yyyy-MM-dd";
	
	private static final String PATTERN_DATE_TIME="\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}";
	
	private static final String PATTERN_DATE_TIME_FORMAT="yyyy-MM-dd HH:mm:ss";
	
	
	
	private DateFormat getDateFormat(String source){
		if(source.matches(PATTERN_DATE)){
			return new SimpleDateFormat(PATTERN_DATE_FORMAT);
		}else if(source.matches(PATTERN_DATE_TIME)){
			return new SimpleDateFormat(PATTERN_DATE_TIME_FORMAT);
		}
		if(source.startsWith("星期")){
			return new SimpleDateFormat(PATTERN_DEFAULT_FORMAT, Locale.SIMPLIFIED_CHINESE);
		}
		return new SimpleDateFormat(PATTERN_DEFAULT_FORMAT);
	}
	
	@Override
	public Date convert(String source) {
		if (source == null || source.isEmpty()) {
			return null;
		}
		try {
			return getDateFormat(source).parse(source);
		} catch (ParseException e) {
			log.error("时间转换失败", e);
		}
		return null;
	}
	
	public static void main(String[] args) {
		System.out.println(new Date());
	}
}
